package com.company.cloud.common.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.dialect.Props;

public class PropertiesUtils {
	
	
	public static Map<String, String> readMapByFile(String filePath) {
		Map<String, String> data=new HashMap<String, String>();
		Properties properties=PropertiesUtils.getPropertiesByFile(filePath);
		for(Object key:properties.keySet()) {
			Object val= properties.get(key);
			if(val!=null) {
				data.put(key.toString(), val.toString());
			}
		}
		return data;
	}
	
	
	public static Set<String> readListByFile(String filePath) {
		return readListByFile(null,filePath);
	}
	
	public static Set<String> readListByFile(String prefix, String filePath) {
		Set<String> data=new HashSet<String>();
		Properties properties=PropertiesUtils.getPropertiesByFile(filePath);
		for(Object key:properties.keySet()) {
			Object val= properties.get(key);
			if(val!=null) {
				if(StrUtil.isEmpty(prefix)) {
					data.add(StrUtil.format("{}={}", key.toString(), val.toString()));
				}else {
					data.add(StrUtil.format("{}{}={}",prefix, key.toString(), val.toString()));
				}
			}
		}
		return data;
	}
	
	public static Set<String> readListByFile(String prefix, Set<String> filePaths) {
		Set<String> data=new HashSet<String>();
		for(String filePath:filePaths) {
			Set<String> propList=readListByFile(prefix, filePath);
			 if(ArrayUtil.isNotEmpty(propList)) {
				 propList.forEach(item->{
					 data.add(item);
				 });
			 }
		}
		return data;
	}
	
	
	
	
	
	public static Properties getPropertiesByFile(String filePath) {
		Properties properties=new Properties();
		try {
			InputStream inStream=new BufferedInputStream(new FileInputStream(new File(filePath)));
			properties.load(inStream);
			return properties;
		} catch (IOException e) {
			e.printStackTrace();
			throw new BusinessException(BaseReturnEnum.SYSTEM_ERROR, e.getMessage());
		}
	}
	
	
	public static Props getPropByFile(String filePath) {
		Props prop=new Props(new File(filePath));
		return prop;
	}
	
//	public static void main(String[] args) {
//		List<String> data=PropertiesUtils.readListByFile("--","/Users/anros/Documents/E/opt/data/application3.properties");
//		System.out.println(JSON.toJSONString(data));
//	}
//	

}
